<script setup>
import {ref} from 'vue'
import channelSelect from './channelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {articleAddService,articleGetDataService,articleRenewDataService} from '@/api/article'
import { ElMessage } from 'element-plus';
import {baseUrl} from '@/utils/request'
import axios from 'axios';
// import { ElMessage } from 'element-plus';
//控制抽屉
const drawer = ref(false)


//准备数据
const formModel = ref({
    title:'',
    cate_id:'',
    cover_img:'',
    content:'',
    state:''
})

const imgUrl=ref('')
const onSelectFile =(uploadFile) =>{
    imgUrl.value =  URL.createObjectURL(uploadFile.raw)
    formModel.value.cover_img = uploadFile.raw
}

//发布
const emit = defineEmits('success')
const onPublish= async(state)=>{
  //存入状态
  formModel.value.state= state
  //修改为formdata对象
  const fd = new FormData()
  for(let key in formModel.value){
    fd.append(key,formModel.value[key])
  }
  // console.log(formModel.value);
  
  //发送请求
  if(formModel.value.id){
    //编辑请求
    await articleRenewDataService(fd.cate_id)
    ElMessage('修改成功')
    drawer.value=false
    emit('success', 'edit') 
  }else{
    //添加
    await articleAddService(fd)
    ElMessage.success('添加成功')
    drawer.value=false
    emit('success','add')
  }
}


//声明编辑器ref
const formRef = ref()

//图片格式转换函数
async function imageUrlToFile(url, fileName) {
        try {
          // 第一步：使用axios获取网络图片数据
          const response = await axios.get(url, { responseType: 'arraybuffer' });
          const imageData = response.data;

          // 第二步：将图片数据转换为Blob对象
          const blob = new Blob([imageData], { type: response.headers['content-type'] });

          // 第三步：创建一个新的File对象
          const file = new File([blob], fileName, { type: blob.type });

          return file;
        } catch (error) {
          console.error('将图片转换为File对象时发生错误:', error);
          throw error;
        }
      }

//区分编辑还是添加
const open = async (row) => {
  drawer.value=true
  //注意涉及到row里面id的，需要设置为row.row.id
    if(row.row.id){
      //回显
      // console.log('huixian');
      const res =  await articleGetDataService(row.row.id)
      // console.log(res);
      formModel.value = res.data.data
      //拼接图片地址回显
      imgUrl.value = baseUrl + formModel.value.cover_img

      //提交后台时，需要转换为file格式
      const file =  await imageUrlToFile(imgUrl.value,formModel.value.cover_img)
      formModel.value.cover_img = file
    }else{
        //重置表单
        formModel.value={
          title:'',
          cate_id:'',
          cover_img:'',
          content:'',
          state:''
        }
        //重置图像和
        imgUrl.value=''
          // editorRef.value.setHTML('') 
    }
}


//暴露方法
defineExpose({
    open
})



</script>

<template>
    <el-drawer
    v-model="drawer"
    title="文章详情"
    size="40%"
    >
    <!-- 表单结构 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select
          v-model="formModel.cate_id"
          width="200%"
        ></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
        class="avatar-uploader"
        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
        :show-file-list="false"
        :auto-upload="false"        
        :on-change="onSelectFile"
        >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
        </el-upload>
      </el-form-item>
      <!-- 文本编辑 -->
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
            <textarea v-model="formModel.content"></textarea>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
    </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>